package com.txd.mofa.shouye.aty;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.v2.WaitDialog;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.adapter.ShouyeAdapter;
import com.txd.mofa.adapter.StaggeredGridAdapter;
import com.txd.mofa.base.BaseAty;
import com.txd.mofa.bean.ShaixuanBean;
import com.txd.mofa.bean.ZhuangtaiBean;
import com.txd.mofa.bean.ZhuangtaiBean2;
import com.txd.mofa.fabu.aty.FabuAty;
import com.txd.mofa.login.BangdingAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.utils.SearchRecordTools;
import com.txd.mofa.view.ShanchuDialog;
import com.txd.mofa.xiangce.models.puzzle.Line;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Layout(R.layout.aty_seach_result)
public class SeachResultAty extends BaseAty {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    EditText tvSeach;
    @BindView(R.id.ll)
    LinearLayout ll;
    RecyclerView recy;
    private TextView tv;
    private LinearLayout ll_sousuo;
    private StaggeredGridAdapter adapter;
    private List<ShaixuanBean> list = new ArrayList<>();
    private ShouyeAdapter shouyeAdapter;
    private String name;
    private ArrayList<Map<String, String>> data;
    private LinearLayout ll_net;
    private NestedScrollView sc;
    private ImageView iv_shan,iv_sou;

    @Override
    public void initViews() {
        super.initViews();

        EventBus.getDefault().register(this);

        iv_sou = findViewById(R.id.iv_sou);
        iv_shan = findViewById(R.id.iv_shan);
        sc = findViewById(R.id.sc);
        ll_net = findViewById(R.id.ll_net);
        ll_sousuo = findViewById(R.id.ll_sousuo);
        tv = findViewById(R.id.tv);
        recy = findViewById(R.id.recy);
        tvSeach = findViewById(R.id.tv_seach);

        StaggeredGridLayoutManager layout = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

        recy.setLayoutManager(layout);


        shouyeAdapter = new ShouyeAdapter(R.layout.item_shouye);
        shouyeAdapter.setEmptyView(getLayoutInflater().inflate(R.layout.text_null, null));
        recy.setAdapter(shouyeAdapter);


        recy.setNestedScrollingEnabled(false);

        http();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void zhuangtai(ZhuangtaiBean2 zhuangtaiBean) {

        List<Map<String, String>> data = shouyeAdapter.getData();

        data.get(zhuangtaiBean.getPos()).put("qiehuan",zhuangtaiBean.getQie());
        data.get(zhuangtaiBean.getPos()).put("collect",zhuangtaiBean.getSc());

        shouyeAdapter.notifyDataSetChanged();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        ll_net.setVisibility(View.GONE);
        sc.setVisibility(View.VISIBLE);
        http();
    }

    @Override
    protected void onResume() {
        super.onResume();

        Huoqu();

        woindex();

    }

    private void woindex() {
        HttpRequest.POST(me, woindex, new Parameter().add("token",token), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        Preferences.getInstance().set(me,"shouji","shouji",data.get("account"));

                    }


                }else {

                }
            }
        });
    }


    @Override
    protected void onNetworkDisConnected() {

        if (flag == false) {
            ll_net.setVisibility(View.VISIBLE);
            sc.setVisibility(View.GONE);
        }
    }

    @Override
    public void initDatas(JumpParameter paramer) {

        name = paramer.getString("name");

        ll_sousuo.setVisibility(View.VISIBLE);
        tv.setText(name);
        tvSeach.setHint("");
        tvSeach.setText(name);

        http();
    }

    private void http() {

        if (!NetUtils.isNetworkAvailable(me)){
            ll_net.setVisibility(View.VISIBLE);
            sc.setVisibility(View.GONE);
        }

        HttpRequest.POST(me, search, new Parameter().add("token", token).add("name", name), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")) {
                        data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));

                        for (int i = 0; i < data.size(); i++) {
                            data.get(i).put("qiehuan","222");
                        }
                        shouyeAdapter.setNewData(data);

                    }

                } else {
                    toast("网络异常");
                }
            }
        });
    }

    public void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        editText.setSelection(editText.length());
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    public void setEvents() {

        iv_sou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchRecordTools.saveSearchHistory(me, tvSeach.getText().toString());
                if (tvSeach.getText().toString().equals("") || tvSeach.getText().toString() == null){
                    tvSeach.setText(name);
                    name = tvSeach.getText().toString();
                }else {
                    name = tvSeach.getText().toString();
                }

                if (name.trim().equals("") || name.trim() == null){
                    Toast.makeText(me, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                http();
                ll_sousuo.setVisibility(View.VISIBLE);
                tv.setText(name);
                tvSeach.setHint("");
                tvSeach.setCursorVisible(false);// 再次点击显示光标
            }
        });
        iv_shan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_sousuo.setVisibility(View.GONE);
                tvSeach.setText("");
                name = "";
                showSoftInputFromWindow(tvSeach);
            }
        });
        ll_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag) {
                    ll_net.setVisibility(View.GONE);
                    sc.setVisibility(View.VISIBLE);
                    http();
                }
            }
        });

        ll_sousuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_sousuo.setVisibility(View.GONE);
                tvSeach.setText(tv.getText().toString());
                showSoftInputFromWindow(tvSeach);
                tvSeach.setCursorVisible(true);

            }
        });


        tvSeach.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                tvSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            SearchRecordTools.saveSearchHistory(me, tvSeach.getText().toString());
                            if (tvSeach.getText().toString().trim().equals("") || tvSeach.getText().toString().trim() == null){
                                tvSeach.setText(name);
                                name = tvSeach.getText().toString();
                            }else {
                                name = tvSeach.getText().toString();
                            }
                            if (name.equals("") || name == null){
                                Toast.makeText(me, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                            }else {
                                http();
                                ll_sousuo.setVisibility(View.VISIBLE);
                                tv.setText(name);
                                tvSeach.setHint("");
                            }
                            return true;
                        }
                        return false;
                    }
                });
            }
        });
        shouyeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                jump(XiangqingAtySousuo.class, new JumpParameter()
                        .put("name", name)
                        .put("page",1)
                        .put("pos",position)
                        .put("zhi",shouyeAdapter.getData()));
            }
        });

        shouyeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_sc:
                        if (Preferences.getInstance().getString(me,"shouji","shouji").equals("")){
                            Intent intent = new Intent(me, BangdingAty.class);
                            intent.putExtra("name","绑定手机号");
                            me.startActivity(intent);
                        }else {
                            if (shouyeAdapter.getData().get(position).get("collect").equals("1")) {
                                ShanchuDialog shanchuDialog = new ShanchuDialog(me, "您确认要取消收藏？", new ShanchuDialog.SignListener() {
                                    @Override
                                    public void shanchu() {

                                        collectHttp(position);
                                    }
                                });
                                shanchuDialog.show();
                            } else {
                                collectHttp(position);
                            }
                        }
                        break;
                    case R.id.iv_qiehuan:
                        if (Preferences.getInstance().getString(me,"shouji","shouji").equals("")){
                            Intent intent = new Intent(me, BangdingAty.class);
                            intent.putExtra("name","绑定手机号");
                            me.startActivity(intent);
                        }else {
                            if (shouyeAdapter.getData().get(position).get("qiehuan").equals("111")) {
                                shouyeAdapter.getData().get(position).put("qiehuan", "222");
                                shouyeAdapter.getData().get(position).put("img", shouyeAdapter.getData().get(position).get("beifen"));
                                shouyeAdapter.notifyDataSetChanged();
                            } else {
                                if (Preferences.getInstance().getString(me, "face_img", "face_img").equals("")) {

                                    jump(FabuAty.class);

                                } else {
                                    shouyeAdapter.getData().get(position).put("beifen", shouyeAdapter.getData().get(position).get("img"));
                                    qiehuan(position);

                                }
                            }
                        }
                        break;
                }
            }
        });

    }
    private void qiehuan(int position) {
        HttpRequest.POST(me, faceChang, new Parameter().add("token",token).add("hair_id",shouyeAdapter.getData().get(position).get("id"))
                .add("user_img_url",Preferences.getInstance().getString(me,"face_img","face_img")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));


                        String fake_img_url = data.get("fake_img_url");

                        String fake_video_url = data.get("fake_video_url");

                        shouyeAdapter.getData().get(position).put("qiehuan","111");

                        shouyeAdapter.getData().get(position).put("img",fake_img_url);
                        shouyeAdapter.getData().get(position).put("video",fake_video_url);
                        shouyeAdapter.notifyDataSetChanged();


                    }else{
                    }

                }else {
                    toast("网络异常");
                }
            }
        });
    }
    private void collectHttp(int position) {
        HttpRequest.POST(me, isCollect, new Parameter().add("token", token).add("hair_id", shouyeAdapter.getData().get(position).get("id")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")) {

                        if (shouyeAdapter.getData().get(position).get("collect").equals("1")) {
                            shouyeAdapter.getData().get(position).put("collect", "2");
                        } else {
                            shouyeAdapter.getData().get(position).put("collect", "1");
                        }
                        shouyeAdapter.notifyDataSetChanged();

                    }
                } else {
                    toast("网络异常");
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }
}
